<template>
    <div class="dashboard-container">
        <!-- 顶部KPI卡片 -->
        <el-row :gutter="24" style="margin-bottom: 20px;">
            <el-col v-for="card in kpiCards" :key="card.label" style="flex: 1;">
                <el-card :body-style="{ padding: '20px', width: 'auto' }" shadow="hover">
                    <div class="kpi-card">
                        <h3>{{ card.value }}</h3>
                        <p>{{ card.label }}</p>
                        <el-tag :type="card.type" size="small">{{ card.trend }}</el-tag>
                    </div>
                </el-card>
            </el-col>
        </el-row>

        <!-- 图表区域 -->
        <el-row :gutter="20">
            <!-- 生产任务状态 -->
            <el-col :span="8">
                <el-card header="生产任务状态" shadow="hover">
                    <div ref="taskChart" class="chart"/>
                </el-card>
            </el-col>

            <!-- 库存预警 -->
            <el-col :span="8">
                <el-card header="安全库存预警" shadow="hover">
                    <el-table :data="lowStockItems" height="300" size="small">
                        <el-table-column label="物料名称" prop="materialName"/>
                        <el-table-column label="当前库存" prop="current"/>
                        <el-table-column label="安全库存" prop="safety"/>
                    </el-table>
                </el-card>
            </el-col>

            <!-- 今日报工趋势 -->
            <el-col :span="8">
                <el-card header="今日生产报工趋势" shadow="hover">
                    <div ref="reportChart" class="chart"/>
                </el-card>
            </el-col>
        </el-row>

        <el-row :gutter="20" style="margin-top: 20px;">
            <!-- 生产计划进度 -->
            <el-col :span="24">
                <el-card header="重点生产计划进度" shadow="hover">
                    <el-table :data="planProgress" size="large">
                        <el-table-column label="计划编号" prop="planCode"/>
                        <el-table-column label="计划名称" prop="planName"/>
                        <el-table-column label="进度" prop="progress">
                            <template #default="{ row }">
                                <el-progress :percentage="row.progress" :stroke-width="12"/>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-card>
            </el-col>
        </el-row>
    </div>
</template>

<script setup>
import {ref, onMounted} from 'vue';
import instance from "@/api/request.js";

const echarts = getCurrentInstance().proxy.$echarts

// KPI 卡片
const kpiCards = ref([
    {label: '当日生产完成率', value: '0%', trend: '↑0%', type: 'success', id: 1},
    {label: '在产任务数', value: '0', trend: '平稳', type: 'primary', id: 2},
    {label: '团队总数', value: '1', trend: '↑1', type: null, id: 3},
    {label: '今日销售金额', value: '¥0', trend: '0', type: 'warning', id: 4},
]);

// 图表引用
const taskChart = ref(null);
const reportChart = ref(null);

// 表格数据
const lowStockItems = ref([]);

async function getLowStockItems() {
    await instance.get("material/index?current=1&size=10").then(async res => {
        let data = res.data.records;
        for (let item of data) {
            if (!item.safetyStock) continue;
            await instance.get(`inventory_s/trees?materialId=${item.materialId}`).then(resp => {
                if (resp.data.records[0]?.quantity <= item.safetyStock) {
                    lowStockItems.value.push({
                        materialName: item.materialName,
                        current: resp.data.records[0].quantity,
                        safety: item.safetyStock
                    })
                }
            })

        }
    })
}


const planProgress = ref([]);
const todayPlan = ref([])
const planStatusData = ref([
    {value: 0, name: '未开始', status: 1},
    {value: 0, name: '生产中', status: 2},
    {value: 0, name: '已取消', status: 3}
])

async function getPlanProgress() {
    await instance.get("/production/plan/page?current=1&size=10").then(async res => {
        let data = res.data.records;
        let planStatusTrue = [];
        for (let item of data) {

            await instance.get(`production/plan/detailByPlanCode?planCode=${item.planCode}`).then(resp => {
                planProgress.value.push({
                    planCode: item.planCode,
                    planName: item.planName,
                    progress: resp.data[0]?.products?.completionRate
                })
            });
            let temp = planStatusData.value.filter(i => i.status === item.planStatus)[0];
            if (temp) {
                temp.value += 1
            }
            if (item.planStatus === 2) {
                planStatusTrue.push(item)
            }
            let startDate = item.startDate
            let nowDay = new Date().getDate();
            let startDay = new Date(startDate).getDate();
            if (nowDay === startDay) {
                todayPlan.value.push(item)
                let findHe = kpiCards.value.filter(card => card.id === 1)[0];
                findHe.value = parseFloat((planStatusTrue.length / todayPlan.value.length * 100).toFixed(2)) + "%"
            }
            if (item.planStatus === 2) {
                let findHe = kpiCards.value.filter(card => card.id === 2)[0];
                findHe.value = parseInt(findHe.value) + 1
            }

        }
    })
}

function getTeamCount() {
    instance.get("team-info/list?current=1&size=10000").then(res => {
        let find = kpiCards.value.filter(card => card.id === 3)[0];
        find.value = res.data.records?.length;
    })
}

function getTodaySaleAmount() {
    instance.get("quotation?current=1&size=10000").then(res => {
        let data = res.data?.records;
        for (let item of data) {
            let nowDay = new Date().getDate();
            let startDay = new Date(item.quotaionShippingTime).getDate();
            if (nowDay === startDay) {
                let find = kpiCards.value.filter(card => card.id === 4)[0];
                find.value = "¥" + (parseFloat(find.value.substring(1, find.value.length)) + parseFloat(item.quotationSalesActually))
            }
        }
    })
}

const todoList = ref([
    {title: '', type: '', tagType: 'info'},
    {title: '', type: '', tagType: 'info'},
    {title: '', type: '', tagType: 'danger'},
    {title: '', type: '', tagType: 'warning'},
]);

// 初始化图表
onMounted(async () => {
    await getPlanProgress();
    await getLowStockItems();
    getTeamCount();
    getTodaySaleAmount();
    // 生产任务状态图
    const taskEchartInstance = echarts.init(taskChart.value);
    taskEchartInstance.setOption({
        tooltip: {trigger: 'item'},
        legend: {top: '5%', left: 'center'},
        series: [
            {
                name: '任务状态',
                type: 'pie',
                radius: ['40%', '70%'],
                avoidLabelOverlap: false,
                label: {show: false},
                emphasis: {
                    label: {show: true, fontSize: 14, fontWeight: 'bold'}
                },
                data: planStatusData.value
            }
        ]
    });

    // 今日报工趋势（折线图）
    const reportEchartInstance = echarts.init(reportChart.value);
    reportEchartInstance.setOption({
        tooltip: {trigger: 'axis'},
        xAxis: {
            type: 'category',
            data: ['08:00', '10:00', '12:00', '14:00', '16:00', '18:00']
        },
        yAxis: {type: 'value'},
        series: [
            {
                name: '报工数量',
                type: 'line',
                data: [0, 0, 0, 0, 0, 0],
                smooth: true,
                areaStyle: {opacity: 0.2}
            }
        ]
    });

    // 窗口 resize 自适应
    window.addEventListener('resize', () => {
        taskEchartInstance.resize();
        reportEchartInstance.resize();
    });
});
</script>

<style scoped>
.dashboard-container {
    padding: 20px;
    background-color: #f5f7fa;
    min-height: 100vh;
}

.kpi-card {
    text-align: center;
}

.kpi-card h3 {
    margin: 0 0 5px 0;
    font-size: 24px;
    color: #1f2d3d;
}

.kpi-card p {
    margin: 0;
    font-size: 14px;
    color: #999;
}

.chart {
    width: 100%;
    height: 300px;
}
</style>